package com.lmuse.xmr.foodspotting.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Statistics {

    /**
     * 求一个list集合中出现字符串次数最多的一项，和此项的出现次数
     *效率很高的统计方法。利用正则表达式统计
     */
    public static String AppearenceMax(List<String> list) {
        String regex;
        Pattern pattern;
        Matcher matcher;
        String tmp = "";
        String tot_str = list.toString();

        int maxCount = 0;
        String maxStr = "";
        for (String str : list) {
            if (tmp.equals(str))
                continue;
            tmp = str;
            regex = str;
            pattern = Pattern.compile(regex);
            matcher = pattern.matcher(tot_str);
            int cnt = 0;
            while (matcher.find()) {
                cnt++;
            }
            if (cnt > maxCount) {
                maxCount = cnt;
                maxStr = str;
            }
        }
        return maxStr;
    }

    /**
     * 在list中模糊搜索string
     * @param string
     * @param list
     * @return
     */
    public static List search(String string, List list){
        List results = new ArrayList();
        Pattern pattern = Pattern.compile(string);
        for(int i=0; i < list.size(); i++){
            Matcher matcher = pattern.matcher(list.get(i).toString());
            if(matcher.find()){
                results.add(list.get(i));
            }
        }
        return results;
    }
}